#!/usr/bin/python3
# coding=utf-8
# atest项目关键功能预研代码

import pyautogui as pg
import time
# from pynput.keyboard import Key, Controller
import win32gui, win32ui, win32con, win32api

import pandas as pd

def ep_enum_wins():
    
    titles = []
    def foo(hwnd,mouse):
            #去掉下面这句就所有都输出了，但是我不需要那么多
        if win32gui.IsWindow(hwnd) and win32gui.IsWindowEnabled(hwnd) and win32gui.IsWindowVisible(hwnd):
            titles.append(win32gui.GetWindowText(hwnd))    
    win32gui.EnumWindows(foo, 0)
    print(len(titles))
    for t in titles:
        print(t)
def ep_screenshot_range():
    '''
    局部截图
    '''    
    pg.moveTo(80,80)
    pg.hotkey('ctrl', 'shift', 's', interval=0.1)
    pg.mouseDown(80,80, duration=0.1)
    pg.moveTo(300,300, duration=0.1)
    pg.mouseUp(300,300)

def ep_key_select1():
    '''
    用按键shift+方向键选中3个字符
    无法实现
        win7 3.6.1
        pyautogui 0.9.38
    可以实现
        win7 3.7
    '''
    pg.keyDown("shift")
    pg.press("right")
    pg.press("right")
    pg.press("right")
    pg.keyUp("shift")

def ep_key_select2():
    '''
    用按键shift+方向键选中3个单词
    无法实现
        win7 3.6.1
        pyautogui 0.9.38
    '''
    pg.keyDown("shift")
    pg.press("right")
    pg.press("right")
    pg.press("right")
    pg.keyUp("shift")


def ep_change_active_win_title(title = u"无标题 - 记事本"):
    '''
    寻找窗体，并修改名字
    '''
    hwnd = win32gui.FindWindow(0, title)
    win32api.SendMessage(hwnd,win32con.WM_SETTEXT,None,u"我是标题")

def ep_change_active_move():
    '''
    寻找窗体，并移动
    '''
    hwnd = win32gui.FindWindow(0, u"无标题 - 记事本",)
    win32gui.MoveWindow(hwnd, 30, 30, 400, 400, True)
def ep_get_window_rect(title=u"无标题 - 记事本",):
    '''
    获取坐标，函数原型是
    BOOL GetWindowRect(
        HWND   hWnd,
        LPRECT lpRect
    );
    但python里将输入参数做了修改
    '''
    hwnd = win32gui.FindWindow(0, title)
    if hwnd:
        rect = win32gui.GetWindowRect(hwnd)
        print(rect)
        return rect

def ep_capture_window(title=u"无标题 - 记事本", filename="a.bmp"):
    '''
    获取坐标，函数原型是
    BOOL GetWindowRect(
        HWND   hWnd,
        LPRECT lpRect
    );
    但python里将输入参数做了修改
    '''
    hwnd = win32gui.FindWindow(0, title)
    # hwnd = win32gui.FindWindow(0, title)
    if 0 == hwnd:
        print("窗口不存在")
        return ;


    rect = win32gui.GetWindowRect(hwnd)
    # 根据窗口句柄获取窗口的设备上下文DC（Divice Context）
    hwndDC = win32gui.GetWindowDC(hwnd)
    # 根据窗口的DC获取mfcDC
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # mfcDC创建可兼容的DC
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建bigmap准备保存图片
    saveBitMap = win32ui.CreateBitmap()
    # 获取监控器信息
    # MoniterDev = win32api.EnumDisplayMonitors(None, None)
    rect = win32gui.GetWindowRect(hwnd)
    # x, y = win32gui.ScreenToClient(hwnd, (rect[0], rect[1]))
    # [x, y, h, w] = rect
    h = rect[3] - rect[1];
    w = rect[2] - rect[0];
    
    
    print(rect, h, w)
    # print w,h　　　#图片大小
    # 为bitmap开辟空间
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    # 高度saveDC，将截图保存到saveBitmap中
    saveDC.SelectObject(saveBitMap)
    # 截取从左上角（0，0）长宽为（w，h）的图片
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename)



def ep_window_full_capture(filename="a.bmp"):
    hwnd = 0 # 窗口的编号，0号表示当前活跃窗口
    # 根据窗口句柄获取窗口的设备上下文DC（Divice Context）
    hwndDC = win32gui.GetWindowDC(hwnd)
    # 根据窗口的DC获取mfcDC
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # mfcDC创建可兼容的DC
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建bigmap准备保存图片
    saveBitMap = win32ui.CreateBitmap()
    # 获取监控器信息
    MoniterDev = win32api.EnumDisplayMonitors(None, None)
    w = MoniterDev[0][2][2]
    h = MoniterDev[0][2][3]
    # print w,h　　　#图片大小
    # 为bitmap开辟空间
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    # 高度saveDC，将截图保存到saveBitmap中
    saveDC.SelectObject(saveBitMap)
    # 截取从左上角（0，0）长宽为（w，h）的图片
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, filename)

# 所有截图最好保证背景没有透明色，这样有利于后期的图像识别


def ep_replay_recode_1(fname='record-2.csv'):
    data = pd.read_csv(fname)
    pg.typewrite(data['key-value'][data['key-action'] == 'down'])


import numpy as np


def ep_replay_recode_2(fname='record-2.csv'):
    hwnd = win32gui.FindWindow(0, u"无标题 - 画图")
    win32gui.SetForegroundWindow(hwnd)  # 窗口调整到前台
    
    
    data = pd.read_csv(fname)

    pg.PAUSE=0.05
    
    pts = np.array([data['rel-x'],data['rel-y']]).T
    rect = win32gui.GetWindowRect(hwnd)
    pts = _cts(rect, pts)
    for i in data.index:
        hwnd = win32gui.FindWindow(0, data.loc[i]['wintitle'])
        if (hwnd):
            win32gui.SetForegroundWindow(hwnd)  # 窗口调整到前台
        if data.loc[i]['mouse-action'] == 'click':
            pg.click(pts[i][0], pts[i][1])
        elif data.loc[i]['mouse-action'] == 'down':
            pg.mouseDown(pts[i][0], pts[i][1], _pause=0.2)
        elif data.loc[i]['mouse-action'] == 'move':
            pg.moveTo(pts[i][0], pts[i][1])
        elif data.loc[i]['mouse-action'] == 'up':
            pg.mouseUp(pts[i][0], pts[i][1], _pause=0.2)
        else:
            print("un know ")
        # print(data.loc[i])
        # print(one)


def _cts(S, pts):
    '''
    S 客户窗口对于屏幕的坐标
    pts 将一大堆相对坐标，原点在客户区左上角，转换成屏幕坐标
    '''
    deta = np.array([S[0] - (-8), S[1]])
    return pts + deta
    pass
def ep_screen_to_client(title=u"无标题 - 画图"):
    hwnd = win32gui.FindWindow(0, title)
    # hwnd = win32gui.FindWindow(0, title)
    if 0 == hwnd:
        print("窗口不存在")
        return ;
    rect = win32gui.GetWindowRect(hwnd)
    x, y = win32gui.ScreenToClient(hwnd, (rect[0], rect[1]))
    x1, y1 = win32gui.ScreenToClient(hwnd, (rect[2], rect[3]))

    print(rect[0], rect[1])
    print(x, y, x1, y1, x1-x, y1-y)
    
    pts = np.array([[2,3]])
    _cts(rect, pts)
def ep_who_is_active_win():
    '''
    获取当前
    GetActiveWindow 只是获取当前程序中(严格地说是线程中)被激活的窗口;
    GetForegroundWindow 是获取当前系统中被激活的窗口.
    '''
    time.sleep(1)
    hwnd = win32gui.GetForegroundWindow()
    print(win32gui.GetWindowText(hwnd))
# get_window_rect()
# change_active_move();
# ep_capture_window(title=u'192.168.1.33 (x11vnc) - VNC Viewer')
# ep_enum_wins()
# ep_get_window_rect()
# ep_window_full_capture()
# ep_change_active_move()
# ep_change_active_win_title(title=u"计算器")
ep_get_window_rect(title=u"计算器")
# ep_replay_recode_2()
# ep_replay_recode_2("wml.csv")
# ep_screen_to_client()
# ep_who_is_active_win()